package com.vietnam.power.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.vietnam.power.constant.GeneralConstant;
import com.vietnam.power.domain.UserInfo;
import com.vietnam.power.domain.UserPrinciple;
import com.vietnam.power.domain.UserSearchCriteria;
import com.vietnam.power.service.FileService;
import com.vietnam.power.service.UserService;

@Controller
@RequestMapping("/admin")
public class UserController {
	private static Logger logger = Logger.getLogger(UserController.class);
	@Autowired
	private MessageSource messageSource;

	@Autowired
	private UserService userService;

	@Autowired
	private FileService fileService;

	@RequestMapping(value = { "/changePassword" }, method = RequestMethod.GET)
	public ModelAndView changePassword(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = false) int id) {
		ModelAndView mav = new ModelAndView("admin/newUser");
		UserInfo u = userService.getUserInfoById(id);
		mav.addObject("userInfo", u);

		mav.addObject("mode", GeneralConstant.MODE_CHANGE_PASSWORD);
		mav.addObject("pageTitle", messageSource.getMessage("admin.user.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/changePassword" }, method = RequestMethod.POST)
	public String changePassword(HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute(value = "userInfo") UserInfo userInfo) {
		userService.changePassword(userInfo);

		UserPrinciple auth = (UserPrinciple) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (userInfo.getId().intValue() == auth.getId()) {
			return "redirect:/login.html";
		}

		return "redirect:/admin/viewUserInfo.html?id=" + userInfo.getId();
	}

	@RequestMapping(value = { "/saveUser" }, method = RequestMethod.POST)
	public String saveUser(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(value = "userInfo") UserInfo userInfo) {
		if (userInfo.getId() != null) {
			List<Integer> deletedFileIds = userService.updateInfo(userInfo);

			UserPrinciple auth = (UserPrinciple) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (userInfo.getId().intValue() == auth.getId()) {
				auth.setAvatarId(userInfo.getAvatarId());
				auth.setFirstName(userInfo.getFirstName());
				auth.setLastName(userInfo.getLastName());
				auth.setTimezone(userInfo.getTimezone());
				auth.setEmail(userInfo.getEmail());
			}
			if (CollectionUtils.isNotEmpty(deletedFileIds)) {
				for (Integer i : deletedFileIds) {
					fileService.deleteFile(i, request.getSession().getServletContext().getRealPath("/"));
				}
			}
		} else {
			userService.createInfo(userInfo);
		}
		return "redirect:/admin/viewUserInfo.html?id=" + userInfo.getId();
	}

	@RequestMapping(value = { "/viewUserInfo" }, method = RequestMethod.GET)
	public ModelAndView viewUserInfo(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = false) int id) {
		ModelAndView mav = new ModelAndView("admin/newUser");
		logger.debug("user id : " + id);

		UserInfo u = userService.getUserInfoById(id);

		mav.addObject("userInfo", u);
		mav.addObject("countryList", userService.getListOfCountries());
		mav.addObject("timezoneList", userService.getListOfTimezones());
		mav.addObject("mode", GeneralConstant.MODE_VIEW);
		mav.addObject("pageTitle", messageSource.getMessage("admin.user.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/updateUser" }, method = RequestMethod.GET)
	public ModelAndView updateUser(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = false) int id) {
		ModelAndView mav = new ModelAndView("admin/newUser");
		logger.debug("user id : " + id);

		UserInfo u = userService.getUserInfoById(id);

		mav.addObject("userInfo", u);
		mav.addObject("countryList", userService.getListOfCountries());
		mav.addObject("timezoneList", userService.getListOfTimezones());
		mav.addObject("mode", GeneralConstant.MODE_EDIT);
		mav.addObject("pageTitle", messageSource.getMessage("admin.user.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/createNewUser" }, method = RequestMethod.GET)
	public ModelAndView createNewUser(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("admin/newUser");

		mav.addObject("userInfo", new UserInfo());
		mav.addObject("countryList", userService.getListOfCountries());
		mav.addObject("timezoneList", userService.getListOfTimezones());
		mav.addObject("pageTitle", messageSource.getMessage("admin.user.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/searchUser" }, method = RequestMethod.GET)
	public ModelAndView searchUser() {
		ModelAndView mav = new ModelAndView("admin/searchUser");

		mav.addObject("searchUser", new UserSearchCriteria());
		mav.addObject("pageTitle", messageSource.getMessage("admin.user.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/searchUser" }, method = RequestMethod.POST)
	public ModelAndView searchUser(@ModelAttribute(value = "searchUser") UserSearchCriteria criteria) {
		ModelAndView mav = new ModelAndView("admin/searchUser");
		UserPrinciple auth = (UserPrinciple) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		criteria.setCurrentUserId(auth.getId());
		mav.addObject("searchUser", criteria);
		mav.addObject("rs", userService.searchUser(criteria));
		mav.addObject("pageTitle", messageSource.getMessage("admin.user.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

}
